

#import "VoiceViewController.h"
#import "CustomerNetworking.h"
#import "FZ_ReMen_ViewController.h"
#import "FZ_ReMen_CollectionViewCell.h"
#import "FZ_TuiJian_TableViewCell_One.h"
#import "FZ_TuiJian_TableViewCell.h"
#import "FZ_TuiJian_TableViewCell_Three.h"
#import "FZ_TuiJian_TableViewCell_Two.h"
#import "FZ_BoFang_Two_ViewController.h"
#import "FZ_BoFang_One_ViewController.h"
#import "FZ_RootModelR.h"
#import "BaseHeader.h"
#import "ChannerModel.h"
#import <MJRefresh.h>
#import "FZ_Dounment.h"
#import "CoreDataManager.h"
#import "FZ_RightCreatViewDongH.h"
#define URLReMen @"http://echosystem.kibey.com/sound/hot?page=1"
#define URLTuiJian @"http://echosystem.kibey.com/hot/sounds"
static BOOL boFangStateFF = YES;
@interface VoiceViewController ()<UIScrollViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UITableViewDataSource,UITableViewDelegate,collectionCellToBoFangXQDelegate,buttonSCDelegate,buttonTDeleDelegate,buttonSCTDelegate,buttonDeleDelegate>
@property (nonatomic ,retain) UIView *viewN;
@property (nonatomic ,retain) UISegmentedControl *segmentControl;
@property (nonatomic ,retain) UIScrollView *scrollV;
@property (nonatomic, retain) UICollectionView *collectionView2;
@property (nonatomic, retain) UITableView *tabelV2;
@property (nonatomic ,retain) NSMutableArray *arrayFirstData;
@property (nonatomic ,retain) NSMutableArray *arrayFirstTotle;
@property (nonatomic ,retain) NSMutableArray *arraySecondDataF;
@property (nonatomic ,retain) NSMutableArray *arraySecondTotleF;
@property (nonatomic ,retain) NSMutableArray *arraySecondDataS;
@property (nonatomic ,retain) NSMutableArray *arraySecondTotleS;
@property (nonatomic ,retain) NSMutableArray *arraySecondDataT;
@property (nonatomic ,retain) NSMutableArray *arraySecondTotleT;
@property (nonatomic ,retain) NSArray *arrayR;
@property (nonatomic ,retain) NSArray *arrayR2;
@property (nonatomic ,retain) NSArray *arrayR3;
@property(nonatomic, assign)NSInteger page;
@property(nonatomic, retain)NSMutableArray *firstArray;
@property (nonatomic, retain) UITapGestureRecognizer *tapTouXiang;
@property (nonatomic ,retain) FZ_RightCreatViewDongH *CreatView;
//@property (nonatomic ,getter=isDragging) BOOL boFangState;
@property(nonatomic, assign)BOOL boFangStateF;
@property (nonatomic ,strong) CoreDataManager *coreDataManagerR;
@property (nonatomic ,retain) FZ_RootModelR *coreModel;
@property (nonatomic ,retain) NSArray *coreResultArray;
@end
@implementation VoiceViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.coreDataManagerR = [CoreDataManager shareManager];
    NSLog(@"url:%@",[_coreDataManagerR applicationDocumentsDirectory]);
    //1
    self.arrayFirstData = [NSMutableArray array];
     //不能开
//    _arrayTotle = [NSMutableArray array];
    
    [CustomerNetworking customerWithURL:URLReMen andParamer:nil andBlock:^(id response) {
        NSDictionary *dic = (NSDictionary *)response;
        self.arrayFirstData = [[dic objectForKey:@"result"] objectForKey:@"data"];
        [self JieXiTuiJianData];
        [_collectionView2 reloadData];
        [_tabelV2 reloadData];
    }];
    
    //2.1
    self.arraySecondDataF = [NSMutableArray array];
    NSDictionary *body1 = @{@"v":@"9",@"period":@"daily"};
    [CustomerNetworking customerWithURL:URLTuiJian andParamer:body1 andBlock:^(id response) {
        NSDictionary *dicc1 = response;
        self.arrayR = [[dicc1 objectForKey:@"result"] objectForKey:@"data"];
        [self JieXiReMenRiData];
        [_collectionView2 reloadData];
        [_tabelV2 reloadData];
    }];
    //2.2
    self.arraySecondDataS = [NSMutableArray array];
    NSDictionary *body2 = @{@"v":@"9",@"period":@"weekly"};
    [CustomerNetworking customerWithURL:URLTuiJian andParamer:body2 andBlock:^(id response) {
        NSDictionary *dicc2 = response;
        self.arrayR2 = [[dicc2 objectForKey:@"result"] objectForKey:@"data"];
        [self JieXiZhouData];
        [_collectionView2 reloadData];
        [_tabelV2 reloadData];
    }];
    //2.3
    self.arraySecondDataT = [NSMutableArray array];
    NSDictionary *body3 = @{@"v":@"9",@"period":@"monthly"};
    [CustomerNetworking customerWithURL:URLTuiJian andParamer:body3 andBlock:^(id response) {
        NSDictionary *dicc3 = response;
        self.arrayR3 = [[dicc3 objectForKey:@"result"] objectForKey:@"data"];
        [self JieXiReMenYueData];
        [_collectionView2 reloadData];
        [_tabelV2 reloadData];
    }];
    [self  createSubView];
    self.firstArray = [NSMutableArray array];
    [self loadData:self.page andLoading:NO];
    [self creatTransLayer];
    
    
}
-(void)creatTransLayer{
    self.CreatView = [[FZ_RightCreatViewDongH alloc] initWithFrame:CGRectMake(0, 0, 36.f, 36.f)];
    self.tapTouXiang = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTouXiangRootVC:)];
    [self.CreatView addGestureRecognizer:self.tapTouXiang];
    [_tapTouXiang release];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.CreatView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotificationK:) name:YINYUE_STATE_K object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotificationT:) name:YINYUE_STATE_T object:nil];
}
- (void)receiveNotificationK:(NSNotification *)notification{
    self.boFangStateF = YES;
}
- (void)receiveNotificationT:(NSNotification *)notification{
    self.boFangStateF = NO;
}
-(void)loadData:(NSInteger)page andLoading:(BOOL)loading{
    [CustomerNetworking customerWithURL:[NSString stringWithFormat:@"http://echosystem.kibey.com/channel/get?with_sound=0&order=hot&page=%ld", page] andParamer:nil andBlock:^(id response) {
        if (loading == NO) {
            [self.firstArray removeAllObjects];
        }
        for (NSDictionary *dic in [[response objectForKey:@"result"] objectForKey:@"data"]) {
            ChannerModel *model = [ChannerModel modelWithDictionary:dic];
            [self.firstArray addObject:model];
        }
        if (self.firstArray.count != 0) {
            [self.collectionView2 reloadData];
        }
        //        [self.collectionView.header endRefreshing];
        //        [self.collectionView.footer endRefreshing];
    }];
}
- (void)JieXiTuiJianData{
    //这块跟上面开为什么不一样
    self.arrayFirstTotle = [NSMutableArray array];
    for (NSDictionary *dic1 in self.arrayFirstData) {
        FZ_RootModelR *Rmodel = [[FZ_RootModelR alloc] init];
        [Rmodel setValuesForKeysWithDictionary:dic1];
        [self.arrayFirstTotle addObject:Rmodel];
        
    }
}
- (void)JieXiReMenRiData{
    self.arraySecondTotleF = [NSMutableArray array];
    for (NSDictionary *dicf in self.arrayR) {
        FZ_RootModelR *Rmodel = [[FZ_RootModelR alloc] init];
        [Rmodel setValuesForKeysWithDictionary:dicf];
        [self.arraySecondTotleF addObject:Rmodel];
    }
}
- (void)JieXiZhouData{
    self.arraySecondTotleS = [NSMutableArray array];
    for (NSDictionary *dic2 in self.arrayR2) {
        FZ_RootModelR *Tmodel = [[FZ_RootModelR alloc] init];
        [Tmodel setValuesForKeysWithDictionary:dic2];
        [self.arraySecondTotleS addObject:Tmodel];
    }
}
- (void)JieXiReMenYueData{
    self.arraySecondTotleT = [NSMutableArray array];
    for (NSDictionary *dic2 in self.arrayR3) {
        FZ_RootModelR *Tmodel = [[FZ_RootModelR alloc] init];
        [Tmodel setValuesForKeysWithDictionary:dic2];
        [self.arraySecondTotleT addObject:Tmodel];
    }
}

- (void)createSubView{
    self.viewN = [[UIView alloc] initWithFrame:CGRectMake(130.f, 5.f, 100.f, 30.f)];
    self.segmentControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"热门",@"推荐", nil]];
    self.segmentControl.frame = CGRectMake(5.f, 6.f, 80.f, 20.f);
    self.segmentControl.selectedSegmentIndex = 0;
    self.segmentControl.tintColor = [UIColor greenColor];
    [_segmentControl addTarget:self action:@selector(segmentCAction:) forControlEvents:UIControlEventValueChanged];
    [self.viewN addSubview:self.segmentControl];
    //防止偏移
    [self setAutomaticallyAdjustsScrollViewInsets:NO];
    self.scrollV = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 114.f)];
    self.scrollV.backgroundColor = [UIColor orangeColor];
    self.scrollV.contentSize = CGSizeMake(self.scrollV.frame.size.width * 2, self.view.frame.size.height - 114.f);
    self.scrollV.bounces = NO;
    self.scrollV.delegate = self;
    self.scrollV.pagingEnabled = YES;
    [self.view addSubview:self.scrollV];
    
    UICollectionViewFlowLayout *flowLayoutTwo = [[UICollectionViewFlowLayout alloc] init];
    
    self.collectionView2 = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.scrollV.frame.size.width, self.scrollV.frame.size.height) collectionViewLayout:flowLayoutTwo];
    self.collectionView2.delegate = self;
    self.collectionView2.dataSource = self;
    self.collectionView2.tag = 10002;
    self.collectionView2.backgroundColor = [UIColor whiteColor];
    [self.scrollV addSubview:self.collectionView2];
    [_collectionView2 release];

    self.tabelV2 = [[UITableView alloc] initWithFrame:CGRectMake(375.f, 0, self.scrollV.frame.size.width, self.scrollV.frame.size.height) style:UITableViewStyleGrouped];
    self.tabelV2.delegate = self;
    self.tabelV2.dataSource = self;
//    self.tabelV2.backgroundColor = [UIColor blackColor];
    [self.scrollV addSubview:self.tabelV2];
    [_tabelV2 release];
    
    self.scrollV.backgroundColor = [UIColor whiteColor];
    [self.scrollV release];
    [_segmentControl release];
 
    self.navigationItem.titleView = _viewN;
    UINib *nibReMen = [UINib nibWithNibName:@"FZ_ReMen_CollectionViewCell" bundle:[NSBundle mainBundle]];

    [self.collectionView2 registerNib:nibReMen forCellWithReuseIdentifier:@"ReMenCell"];
    [self.tabelV2 registerClass:[FZ_TuiJian_TableViewCell class] forCellReuseIdentifier:@"TuiJianTableViewCell"];
    
    
    UINib *nibTuiJianTwo = [UINib nibWithNibName:@"FZ_TuiJian_TableViewCell_Two" bundle:[NSBundle mainBundle]];
    [self.tabelV2 registerNib:nibTuiJianTwo forCellReuseIdentifier:@"FZ_TuiJian_TableViewCell_Two"];
    
    UINib *nibTuiJianThree = [UINib nibWithNibName:@"FZ_TuiJian_TableViewCell_Three" bundle:[NSBundle mainBundle]];
    [self.tabelV2 registerNib:nibTuiJianThree forCellReuseIdentifier:@"FZ_TuiJian_TableViewCell_Three"];
    
    self.collectionView2.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(VCRefresh)];
    
}
- (void)VCRefresh{
    self.arrayFirstTotle = [NSMutableArray array];
    [self JieXiTuiJianData];
    NSLog(@"3");
    [self.collectionView2.header endRefreshing];
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(171.f, 220.f);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    
    return UIEdgeInsetsMake(10, 10, 0, 10);
    
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
        if (0 != self.arrayFirstTotle.count) {
            return self.arrayFirstTotle.count;
        }
    return 12;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    FZ_RootModelR *model = self.arrayFirstTotle[indexPath.row];
    FZ_ReMen_CollectionViewCell *cell1 = [collectionView dequeueReusableCellWithReuseIdentifier:@"ReMenCell" forIndexPath:indexPath];
    cell1.model = model;
    return cell1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
//        if (self.arraySecondTotleF.count != 0) {
//            return self.arraySecondTotleF.count;
//        }else{
            return 1;
//        }
    }
    if (section == 1) {
        if (self.arraySecondTotleS.count != 0) {
            return self.arraySecondTotleS.count;
        }else{
            return 1;
        }
    }
    else{
        if (self.arraySecondTotleT.count != 0) {
            return self.arraySecondTotleT.count;
        }else{
            return 1;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        FZ_TuiJian_TableViewCell_One *cell1 = [FZ_TuiJian_TableViewCell_One presentTabelViewCell:tableView];
        cell1.delegate = self;
        FZ_RootModelR *modelF = self.arraySecondTotleF[indexPath.row];
        cell1.jieShouModel = modelF;
        cell1.arrayJieShou = self.arraySecondTotleF;
        //        cell1.backgroundColor = [UIColor orangeColor];
        cell1.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell1;
    }
    if (indexPath.section == 1) {
        //        if (indexPath.row == 0) {
        FZ_TuiJian_TableViewCell_Two *cell2 = [tableView dequeueReusableCellWithIdentifier:@"FZ_TuiJian_TableViewCell_Two"];
        cell2.selectionStyle = UITableViewCellSelectionStyleNone;
        FZ_RootModelR *modelS = self.arraySecondTotleS[indexPath.row];
        cell2.jieShouModelS = modelS;
        cell2.delegate = self;
        cell2.delegateD = self;
        return cell2;
        //        }else{
        //            return nil;
        //        }
        
    }
    else{
        //        if (indexPath.row == 0) {
        FZ_TuiJian_TableViewCell_Three *cell3 = [tableView dequeueReusableCellWithIdentifier:@"FZ_TuiJian_TableViewCell_Three"];
        FZ_RootModelR *modelT = self.arraySecondTotleT[indexPath.row];
        cell3.jieShouModelT = modelT;
        cell3.delegateT = self;
        cell3.delegateDT = self;
        cell3.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell3;
        //        }else{
        //            return nil;
        //        }
        
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 400.f;
    }else
        if (indexPath.section == 1) {
            return 57.f;
        }
        else{
            return 57.f;
        }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    FZ_BoFang_One_ViewController *boFangOne = [[FZ_BoFang_One_ViewController alloc] init];
    FZ_RootModelR *Imodel = self.arrayFirstTotle[indexPath.row];
    boFangOne.Imodel = Imodel;
    boFangOne.indexRowF = indexPath.row;
    boFangOne.arrayF = self.arrayFirstTotle;
    
    
    self.coreModel = Imodel;
    [self CoreR];
    
    if (self.firstArray.count != 0) {
        ChannerModel *modelC = self.firstArray[indexPath.row];
        boFangOne.PicID = modelC.ID;
    }
    [self.navigationController pushViewController:boFangOne animated:YES];
    [boFangOne release];
}

- (void)CoreR{
  FZ_Dounment  *modelF = [NSEntityDescription insertNewObjectForEntityForName:@"FZ_Dounment" inManagedObjectContext:self.coreDataManagerR.managedObjectContext];
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"FZ_Dounment" inManagedObjectContext:_coreDataManagerR.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS '%@'", self.coreModel.name];
    [fetchRequest setPredicate:predicate];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    NSError *error = nil;
    NSArray *fetchedObjects = [_coreDataManagerR.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    self.coreResultArray = fetchedObjects;
    if (fetchedObjects == nil) {
        NSLog(@"error:%@",error);
    }
    else{
        for (FZ_Dounment *coreModelF  in fetchedObjects) {
            NSLog(@"name :%@,pic:%@,source:%@",coreModelF.name,coreModelF.pic,coreModelF.source);
        }
    }

//    for (FZ_Dounment *modelD in self.coreResultArray) {
    if (0 == self.coreResultArray.count) {
        modelF .name = self.coreModel.name;
        modelF.pic = self.coreModel.pic;
        modelF.source = self.coreModel.source;
        [self.coreDataManagerR saveContext];
    }
//        if (modelD.name != self.coreModel.name) {
//        }
//    }
}


- (void)buttonSCTModel:(FZ_RootModelR *)model{
    self.coreModel = model;
    [self CoreR];

}
- (void)buttonDeleTModel:(FZ_RootModelR *)model{
    self.coreModel = model;

}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10.f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FZ_BoFang_One_ViewController *boFang = [[FZ_BoFang_One_ViewController alloc] init];
    if (indexPath.section == 1) {
        boFang.Imodel = self.arraySecondTotleS[indexPath.row];
        
    }
    if (indexPath.section == 2) {
        boFang.Imodel = self.arraySecondTotleT[indexPath.row];
    }
    [self.navigationController pushViewController:boFang animated:YES];
    [boFang release];
}

- (void)viewWillAppear:(BOOL)animated{
    self.boFangStateF = boFangStateFF;
    if (self.boFangStateF) {
        self.CreatView = [[FZ_RightCreatViewDongH alloc] initWithFrame:CGRectMake(0, 0, 36.f, 36.f)];
        self.tapTouXiang = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTouXiangRootVC:)];
        [self.CreatView addGestureRecognizer:self.tapTouXiang];
        [_tapTouXiang release];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.CreatView];
    }else{
        [self.CreatView removeAnimat];
    }
}

- (void)tapTouXiangRootVC:(UITapGestureRecognizer *)sender{
    FZ_BoFang_Two_ViewController *boFangTwo = [FZ_BoFang_Two_ViewController sharePlayer];
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController pushViewController:boFangTwo animated:YES];
    [boFangTwo release];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if ([scrollView isKindOfClass:[UITableView class]]) {
        return;
    }
}

- (void)segmentCAction:(UISegmentedControl *)sender
{
    if ( 0  == sender.selectedSegmentIndex) {
        self.scrollV.contentOffset = CGPointMake(0, 0);
    }
    else{
        self.scrollV.contentOffset = CGPointMake(self.scrollV.frame.size.width, 0);
    }
}

- (void)collectionCellToBoFangXQ:(NSArray *)array andModel:(FZ_RootModelR *)model{
    FZ_BoFang_One_ViewController *boFangOneViewController = [[FZ_BoFang_One_ViewController alloc] init];
    boFangOneViewController.Imodel = model;
    [self.navigationController pushViewController:boFangOneViewController animated:YES];
    [boFangOneViewController release];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if ([scrollView isKindOfClass:[UIScrollView class]]) {
        CGFloat yy = scrollView.contentOffset.y;
        if (yy > 375.f) {
            self.segmentControl.selectedSegmentIndex = 0;
        }
        else{
            self.segmentControl.selectedSegmentIndex = 1;
        }
    }
}

- (void)buttonSCModel:(FZ_RootModelR *)model{
    self.coreModel = model;
    [self CoreR];
}
- (void)buttonDeleModel:(FZ_RootModelR *)model{
    self.coreModel = model;
    NSLog(@"删除");
}

@end
